package com.xmu.prcs.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.xmu.prcs.action.bean.PostBean;
import com.xmu.prcs.action.bean.TopicBean;
import com.xmu.prcs.action.bean.UserInfoBean;
import com.xmu.prcs.action.bean.UserReplyBean;
import com.xmu.prcs.dao.PostDao;
import com.xmu.prcs.dao.ReplyDao;
import com.xmu.prcs.dao.TopicDao;
import com.xmu.prcs.dao.UserDao;
import com.xmu.prcs.entity.Post;
import com.xmu.prcs.entity.Reply;
import com.xmu.prcs.entity.Topic;
import com.xmu.prcs.entity.User;
import com.xmu.prcs.service.ForumManager;
import com.xmu.prcs.util.DictionaryUtil;
import com.xmu.prcs.util.PageBean;
import com.xmu.prcs.util.ResultBean;

public class ForumManagerImpl implements ForumManager {

	private TopicDao topicDao;
	
	private PostDao postDao;
	
	private ReplyDao replyDao;
	
	private UserDao userDao;

	public TopicDao getTopicDao() {
		return topicDao;
	}

	public void setTopicDao(TopicDao topicDao) {
		this.topicDao = topicDao;
	}

	public PostDao getPostDao() {
		return postDao;
	}

	public void setPostDao(PostDao postDao) {
		this.postDao = postDao;
	}

	public ReplyDao getReplyDao() {
		return replyDao;
	}

	public void setReplyDao(ReplyDao replyDao) {
		this.replyDao = replyDao;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public ResultBean getTopic4Page(PageBean page) {
		int count = topicDao.countTopics();
		PageBean pagebean = new PageBean(count);
		pagebean.setCurrentPage(page.getCurrentPage());
		
		List<Topic> topicList = topicDao.find4page(page.getBeginIndex(), page.getPageSize());
		List<TopicBean> beanList = new ArrayList<TopicBean>();
		if(topicList != null && topicList.size() != 0){
			TopicBean bean = new TopicBean();
			for(Topic topic : topicList){
				bean = this.topicEntity2Bean(topic);
				beanList.add(bean);
			}
		}
		
		ResultBean result = new ResultBean();
		result.setPage(pagebean);
		result.setContent(beanList);
		return result;
	}
	
	/**
	 * 话题实体转换成页面bean
	 * @param topic
	 * @return
	 */
	public TopicBean topicEntity2Bean(Topic topic){
		TopicBean bean = new TopicBean();
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		
		bean.setIdTopic(topic.getIdTopic());
		bean.setNote(topic.getNote());
		bean.setTopicName(topic.getTopicName());
		bean.setPostNumber(topic.getPostNumber());
		Set<User> charge = topic.getChargePersons();
		if(charge != null && charge.size() != 0){
			String chargePerson = "";
			for(User user : charge){
				chargePerson += user.getUserName() + " ";
			}
			bean.setChargePersons(chargePerson.trim());
		}
		Post post = postDao.getLastestPostOfTopic(topic.getIdTopic());
		if(post != null){
			bean.setLastPostAuthor(post.getAutherName());
			bean.setLastPostName(post.getPostName());
			bean.setLastPostTime(format.format(post.getCreateTime()));
			bean.setLastPostId(post.getIdPost());
		}
		return bean;
	}

	public List<TopicBean> getAllTopic() {
		List<TopicBean> topicBeans = new ArrayList<TopicBean>();
		List<Topic> topics = topicDao.getAll();
		if(topics != null && topics.size() != 0){
			TopicBean bean;
			for(Topic topic : topics){
				bean = this.topicEntity2Bean(topic);
				topicBeans.add(bean);
			}
		}
		return topicBeans;
	}
	
	public TopicBean getTopicById(int topicId){
		TopicBean bean = new TopicBean();
		Topic topic = topicDao.get(topicId);
		if(topic != null){
			bean = this.topicEntity2Bean(topic);
		}
		return bean;
	}
	
	public boolean isTopicNameExist(String topicName){
		List<Topic> list = topicDao.getByProperty(TopicDao.TOPIC_NAME, topicName);
		if(list != null && list.size() != 0){
			return true;
		}
		return false;
	}

	public boolean addTopic(TopicBean bean, List<String> chargePerson) {
		Topic topic = new Topic();
		topic.setNote(bean.getNote());
		topic.setPostNumber(0);
		topic.setTopicName(bean.getTopicName());
		topic.setUpdateTime(new Date());
		
		Set<User> chargeUser = new HashSet<User>();
		if(chargePerson != null && chargePerson.size() != 0){
			User user;
			for(String userId : chargePerson){
				user = userDao.get(Integer.parseInt(userId));
				chargeUser.add(user);
			}
			topic.setChargePersons(chargeUser);
		}
		
		topicDao.save(topic);
		return false;
	}

	public boolean modifyTopic(TopicBean bean, List<String> chargePerson) {
		Topic topic = topicDao.get(bean.getIdTopic());
		topic.setNote(bean.getNote());
		topic.setTopicName(bean.getTopicName());

		Set<User> chargeUser = new HashSet<User>();
		if(chargePerson != null && chargePerson.size() != 0){
			User user;
			for(String userId : chargePerson){
				user = userDao.get(Integer.parseInt(userId));
				chargeUser.add(user);
			}
			topic.setChargePersons(chargeUser);
		}
		topicDao.update(topic);
		return false;
	}
	
	public List<UserInfoBean> getChargePersonOfTopic(int topicId){
		if(topicId <= 0){
			return null;
		}
		List<UserInfoBean> userList = new ArrayList<UserInfoBean>();
		Topic topic = topicDao.get(topicId);
		Set<User> chargePerson = topic.getChargePersons();
		if(chargePerson != null && chargePerson.size() != 0){
			for(User user : chargePerson){
				UserInfoBean bean = new UserInfoBean();
				bean.setUserId(user.getIdUser());
				bean.setName(user.getUserName());
				userList.add(bean);
			}
		}
		return userList;
	}
	
	public boolean deleteTopic(int topicId){
		if(topicId <= 0){
			return false;
		}
		topicDao.remove(topicId);
		return true;
	}

	public ResultBean getPost4Page(PageBean page, int topicId, int userId) {
		int count = postDao.countPost(topicId);
		PageBean pagebean = new PageBean(count);
		pagebean.setCurrentPage(page.getCurrentPage());
		
		List<Post> postList = postDao.find4Page(page.getBeginIndex(), page.getPageSize(),topicId);
		List<PostBean> beanList = new ArrayList<PostBean>();
		if(postList != null && postList.size() != 0){
			for(Post post : postList){
				PostBean bean = new PostBean();
				bean = this.postEntity2Bean(post);
				if(userId > 0){
					User user = userDao.get(userId);
					if(user.getUserName().equals(bean.getAutherName())){
						bean.setIsAuther(1);
					}
				}
				beanList.add(bean);
			}
		}
		ResultBean result = new ResultBean();
		result.setPage(pagebean);
		result.setContent(beanList);
		return result;
	}
	
	/**
	 * 帖子实体转换成页面bean
	 * @param post
	 * @return
	 */
	public PostBean postEntity2Bean(Post post){
		PostBean bean = new PostBean();
		if(post != null){
			SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			bean.setAutherName(post.getAutherName());
			
			bean.setBrowseNumber(post.getBrowseNumber());
			bean.setCreateTime(format.format(post.getCreateTime()));
			bean.setIdPost(post.getIdPost());
			if(post.getLastReplyTime() != null){
				bean.setLastReplyTime(format.format(post.getLastReplyTime()));
				bean.setLastReplyUserName(post.getLastReplyUserName());
			}
			bean.setPostName(post.getPostName());
			bean.setReplyNumber(post.getReplyNumber());
			bean.setContent(post.getContent());
		}
		return bean;
	}

	public boolean addPost(PostBean postBean, int topicId, int userId) {
		Post post = new Post();
		Date date = new Date();
		post.setAutherName(postBean.getAutherName());
		post.setBrowseNumber(0);
		post.setContent(postBean.getContent());
		post.setCreateTime(date);
		post.setPostName(postBean.getPostName());
		post.setReplyNumber(0);
		post.setLastReplyTime(date);
		
		User user = userDao.get(userId);
		post.setAutherName(user.getUserName());
		post.setLastReplyUserName(user.getUserName());
		
		postDao.save(post);
		postDao.flush();
		
		Reply reply = new Reply();
		reply.setAuther(user);
		reply.setContent(postBean.getContent());
		reply.setReplyTime(date);
		replyDao.save(reply);
		replyDao.flush();
		
		Set<Reply> replys = new HashSet<Reply>();
		replys.add(reply);
		post.setReplys(replys);
		postDao.update(post);
		
		Topic topic = topicDao.get(topicId);
		Set<Post> posts = topic.getPosts();
		posts.add(post);
		topic.setPosts(posts);
		topic.setPostNumber(topic.getPostNumber() + 1);
		topicDao.update(topic);
		return true;
	}

	public boolean deletePost(int postId, int topicId) {
		postDao.remove(postId);
		Topic topic = topicDao.get(topicId);
		topic.setPostNumber(topic.getPostNumber() - 1);
		return true;
	}

	
	public boolean isPostNameExist(String name){
		List<Post> list = postDao.getByProperty(PostDao.POST_NAME, name);
		if(list != null && list.size() != 0){
			return true;
		}
		return false;
	}
	
	public PostBean getPostById(int postId){
		PostBean bean = new PostBean();
		Post post = postDao.get(postId);
		if(post != null){
			bean = this.postEntity2Bean(post);
		}
		return bean;
	}
	
	public boolean modifyPost(PostBean bean){
		Post post = postDao.get(bean.getIdPost());
		post.setContent(bean.getContent());
		post.setPostName(bean.getPostName());
		postDao.update(post);
		return true;
	}

	public boolean addReply2Post(int postId, UserReplyBean userReply, int userId, int replyTo) {
		User user = userDao.get(userId);
		Date date = new Date();
		
		Reply reply = new Reply();
		reply.setAuther(user);
		reply.setContent(userReply.getContent());
		reply.setReplyTime(date);
		reply.setReplyTo(replyTo);
		
		replyDao.save(reply);
		Post post = postDao.get(postId);
		post.setLastReplyTime(date);
		post.setLastReplyUserName(user.getUserName());
		post.setReplyNumber(post.getReplyNumber() + 1);
		Set<Reply> replys = post.getReplys();
		if(replys == null || replys.size() == 0){
			replys = new HashSet<Reply>();
		}
		replys.add(reply);
		post.setReplys(replys);
		return false;
	}

	public boolean deleteReply(int postId, int replyId) {
		replyDao.remove(replyId);
		Post post = postDao.get(postId);
		post.setReplyNumber(post.getReplyNumber() - 1);
		postDao.update(post);
		return false;
	}

	public ResultBean showReplysOfPost(int postId, PageBean page, int userId) {
		int count = replyDao.countReply(postId);
		PageBean pagebean = new PageBean(count);
		pagebean.setCurrentPage(page.getCurrentPage());
		
		List<Reply> replyList = replyDao.get4Page(postId, page.getBeginIndex(), page.getPageSize());
		List<UserReplyBean> beanList = new ArrayList<UserReplyBean>();
		if(replyList != null && replyList.size() != 0){
			for(Reply reply : replyList){
				UserReplyBean bean = this.replyEntity2Bean(reply);
				if(bean.getIdUser() == userId){
					bean.setIsAuther(1);
				}
				beanList.add(bean);
			}
		}
		ResultBean result = new ResultBean();
		result.setPage(pagebean);
		result.setContent(beanList);
		
		Post post = postDao.get(postId);
		post.setBrowseNumber(post.getBrowseNumber() + 1);
		postDao.update(post);
		
		return result;
	}
	
	/**
	 * reply实体类转换成页面bean
	 * @param reply
	 * @return
	 */
	public UserReplyBean replyEntity2Bean(Reply reply){
		UserReplyBean bean = new UserReplyBean();
		if(reply != null){
			SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			bean.setIdReply(reply.getIdReply());
			bean.setReplyTime(format.format(reply.getReplyTime()));
			
			User user = reply.getAuther();
			bean.setEgg(user.getEgg());
			bean.setFlower(user.getFlower());
			bean.setIdUser(user.getIdUser());
			if(user.getPhoto().equals(DictionaryUtil.DEFAULT_PHOTO)){
				bean.setPhoto(DictionaryUtil.DEFAULT_PHOTO_PATH);
			}else{
				bean.setPhoto(user.getPhoto());
			}
			bean.setUserName(user.getUserName());
			bean.setSignature(user.getSignature());
			String content = "";
			if(reply.getReplyTo() != null && reply.getReplyTo() > 0){
				Reply replyTo = replyDao.get(reply.getReplyTo());
				content = "<span class='quote'>“</span>"
						+ replyTo.getContent() 
						+ "<span class='quote'>”</span><br/><br/>";
			}
			bean.setContent(content + reply.getContent());
		}
		return bean;
	}
	
	public int countReply(int postId){
		int count = replyDao.countReply(postId);
		return count;
	}
	
	public int isChargePerson(int topicId, int userId){
		Topic topic = topicDao.get(topicId);
		User user = userDao.get(userId);
		if(topic != null && user != null){
			if(topic.getChargePersons() == null){
				return 0;
			}
			if(topic.getChargePersons().contains(user)){
				return 1;
			}
		}
		return 0;
	}
}
